package com.mybatis.MybatisUtil;

import com.mybatis.dao.NewsMapper;
import com.mybatis.dao.UsersMapper;
import javafx.beans.value.ObservableBooleanValue;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;


import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {

    static ThreadLocal<SqlSession> THREAD_LOCAL = new ThreadLocal<>();

    static final String CONF_FIVE ="mybatis-config.xml";

    //工厂
    static SqlSessionFactory factory = null;
    //静态代码块中初始化

    static boolean factoryEable = false ;


    static {

        factoryEable = createFactory();
    }


    public static boolean createFactory(){

        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        try {
            InputStream inputStream  = Resources.getResourceAsStream(CONF_FIVE);
            factory = builder.build(inputStream);



        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        return true;



    }


    public  static SqlSession  open(){

        SqlSession session = THREAD_LOCAL.get();

        if(session==null){

            session = factory.openSession();

            THREAD_LOCAL.set(session);

        }

          return session;
    }
    public static void close(){

        SqlSession session = THREAD_LOCAL.get();

        if (session != null){
            session.close();

            THREAD_LOCAL.set(null);
        }



    }
    public static void commit(){

        SqlSession session = THREAD_LOCAL.get();

        if (session !=null){
            session.commit();
        }

    }
    public static void rollback(){

        SqlSession session = THREAD_LOCAL.get();

        if (session !=null){
            session.rollback();
        }

    /*    Class<UsersMapper> cl = UsersMapper.class;//类的类型

        UsersMapper dao = session.getMapper(cl);

        NewsMapper dao1 = session.getMapper(NewsMapper.class);*/

      /*  Class<UsersMapper> cl = UsersMapper.class;

        getMapper(cl);*/



    }
    public static <T> T getMapper(Class<T> tClass){

         return open().getMapper(tClass);

    }



}